package LinkedList;

public class DeleteNodeFromLast {
    public static void main(String[] args) {
        ListNode node1=new ListNode(1);
        node1.next=new ListNode(2);
        node1.next.next=new ListNode(3);
        node1.next.next.next=new ListNode(4);
        node1.next.next.next.next=new ListNode(5);
        DeleteNodeFromLast solution=new DeleteNodeFromLast();
        ListNode res=solution.deleteNodeFromLast(node1,5);
        while(res!=null){
            System.out.println(res.val);
            res=res.next;
        }

    }
    public ListNode deleteNodeFromLast(ListNode head,int n){
        ListNode dummyHead=new ListNode(-1);
        dummyHead.next=head;
        ListNode fast=dummyHead;
        ListNode slow=dummyHead;
        for(int i=0;i<=n;i++){
            fast=fast.next;
        }
        while(fast!=null){
            fast=fast.next;
            slow=slow.next;
        }
        if(slow.next!=null){
            slow.next=slow.next.next;
        }
        return dummyHead.next;
    }
}
